﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Linq.Expressions;

namespace InnovTech.Util
{
    /// <summary>
    /// Represents an action and uses a WeakReference to manage the its target.
    /// </summary>
    public class WeakAction : WeakReference
    {
        /// <summary>
        /// Represents the WeakReference of the Action.
        /// </summary>
        WeakReference _expr;

        public WeakAction(object target, Expression<Action> action)
            :base(target)
        {
            _expr = new WeakReference(action.Body);
        }

        /// <summary>
        /// Invokes the Action of this object.
        /// </summary>
        /// <param name="args"></param>
        public void Invoke(params object[] args)
        {
            if (IsAlive)
            {
                Delegate compiled = Expression.Lambda(_expr.Target as Expression).Compile();
                compiled.DynamicInvoke(args);
            }

        }
       
    }
}
